"""
飞书 FastAPI 路由
定义飞书相关的API路由（FastAPI版本）
"""

import json
import logging
from typing import Dict, Any
from fastapi import APIRouter, HTTPException, Request, Header
from fastapi.responses import JSONResponse, RedirectResponse
from src.containers import get_feishu_service
from src.config import feishu_settings
from src.feishu.models import FeishuWebhookMessage, FeishuMessageEvent

logger = logging.getLogger(__name__)

# 创建路由器
router = APIRouter(prefix="/feishu", tags=["飞书集成"])

# 获取飞书服务实例
feishu_service = get_feishu_service()


async def _handle_event(event_data: Dict[str, Any]) -> Dict[str, Any]:
    """处理事件回调"""
    event_type = event_data.get('type')
    
    if event_type == 'message':
        return await _handle_message_event(event_data)
    elif event_type == 'app_ticket':
        # 处理应用票据事件
        return {"message": "App ticket received"}
    else:
        return {"message": f"Event {event_type} received"}


async def _handle_message_event(event_data: Dict[str, Any]) -> Dict[str, Any]:
    """处理消息事件"""
    try:
        message_event = FeishuMessageEvent.from_dict(event_data)
        
        # 只处理文本消息
        if message_event.message_type != 'text':
            return {"message": "Non-text message ignored"}
        
        # 提取消息内容
        content = json.loads(message_event.content)
        text = content.get('text', '').strip()
        
        if not text:
            return {"message": "Empty message"}
        
        # 获取发送者信息
        sender_id = message_event.sender.get('sender_id', {}).get('user_id')
        if not sender_id:
            return {"message": "No sender ID"}
        
        # 调用AI处理消息
        # 这里可以调用现有的API服务
        # 例如: 调用 api_agent.process_question(session_id, text)
        
        # 暂时先返回一个简单的响应
        response_text = f"收到您的消息: {text}\n我正在处理中..."
        
        # 发送回复消息
        feishu_service.send_text_message(sender_id, response_text)
        
        return {"message": "Message processed"}
        
    except Exception as e:
        logger.error(f"消息事件处理错误: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/webhook")
async def webhook(
    request: Request,
    x_lark_request_timestamp: str = Header(None),
    x_lark_request_nonce: str = Header(None),
    x_lark_signature: str = Header(None)
):
    """飞书Webhook入口"""
    try:
        # 获取请求体
        body_bytes = await request.body()
        body_text = body_bytes.decode('utf-8')
        
        # 验证签名
        if not feishu_service.verify_signature(
            x_lark_request_timestamp, 
            x_lark_request_nonce, 
            x_lark_signature, 
            body_text
        ):
            raise HTTPException(status_code=401, detail="Invalid signature")
        
        # 解析JSON数据
        try:
            data = json.loads(body_text)
        except json.JSONDecodeError:
            raise HTTPException(status_code=400, detail="Invalid JSON")
        
        # 解析Webhook消息
        webhook_msg = FeishuWebhookMessage.from_dict(data)
        
        # 处理挑战验证
        if webhook_msg.challenge:
            return {"challenge": webhook_msg.challenge}
        
        # 处理消息事件
        if webhook_msg.type == "event_callback" and webhook_msg.event:
            return await _handle_event(webhook_msg.event)
        
        return {"message": "Webhook received"}
        
    except Exception as e:
        logger.error(f"Webhook处理错误: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/oauth/authorize")
async def oauth_authorize():
    """飞书OAuth授权入口"""
    if not getattr(feishu_settings, 'FEISHU_OAUTH_ENABLED', True):
        raise HTTPException(status_code=403, detail="OAuth is not enabled")
    
    # 构建飞书OAuth授权URL
    auth_url = (
        f"https://open.feishu.cn/open-apis/authen/v1/authorize"
        f"?app_id={feishu_settings.APP_ID}"
        f"&redirect_uri={getattr(feishu_settings, 'FEISHU_REDIRECT_URI', 'http://127.0.0.1:5000/feishu/oauth/callback')}"
        "&response_type=code"
        "&scope=contact:user.base:readonly contact:user.employee_id:readonly contact:user.email:readonly"
    )
    
    return RedirectResponse(url=auth_url)


@router.get("/oauth/callback")
async def oauth_callback(code: str):
    """飞书OAuth回调处理"""
    if not getattr(feishu_settings, 'FEISHU_OAUTH_ENABLED', True):
        raise HTTPException(status_code=403, detail="OAuth is not enabled")
    
    if not code:
        raise HTTPException(status_code=400, detail="Authorization code not provided")
    
    try:
        # 处理OAuth回调，获取访问令牌
        oauth_token = feishu_service.handle_oauth_callback(code)
        
        # 这里可以保存用户信息到数据库或会话中
        # 例如: save_user_session(oauth_token)
        
        return {
            "message": "OAuth successful",
            "user_id": oauth_token.user_id,
            "name": oauth_token.name,
            "email": oauth_token.email
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/health")
async def health_check():
    """飞书服务健康检查"""
    try:
        # 尝试获取应用访问令牌来验证配置
        token = feishu_service.get_app_access_token()
        return {
            "status": "healthy",
            "app_id": feishu_settings.APP_ID,
            "has_verification_token": bool(getattr(feishu_settings, 'VERIFICATION_TOKEN', '')),
            "has_encrypt_key": bool(getattr(feishu_settings, 'FEISHU_ENCRYPT_KEY', ''))
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/send-test")
async def send_test_message(request: Request):
    """发送测试消息（仅用于开发测试）"""
    try:
        # 解析JSON数据
        data = await request.json()
        
        if not data:
            raise HTTPException(status_code=400, detail="No JSON data provided")
        
        user_id = data.get('user_id')
        message = data.get('message')
        
        if not user_id or not message:
            raise HTTPException(status_code=400, detail="user_id and message are required")
        
        try:
            result = feishu_service.send_text_message(user_id, message)
            return {
                "message": "Test message sent",
                "result": result
            }
        except Exception as e:
            raise HTTPException(status_code=500, detail=str(e))
    except json.JSONDecodeError:
        raise HTTPException(status_code=400, detail="Invalid JSON data")
    except Exception as e:
        raise HTTPException(status_code=400, detail=f"JSON解析错误: {str(e)}")